﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CalemShop.Classes;
using System.Media;

namespace CalemShop.Forms
{
    public partial class FrmImportItemFromBarcode : FrmBaseDock
    {

        SoundPlayer sound = null;
        public FrmImportItemFromBarcode()
        {
            InitializeComponent();
            sound = new SoundPlayer(RuntimeData.GetSoundCompletePath());
        }

        public FrmImportItemFromBarcode(FrmCalemShop shop)
            : base(shop)
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            sound = new SoundPlayer(RuntimeData.GetSoundCompletePath());
        }


        private void FrmImportItemFromBarcode_Load(object sender, EventArgs e)
        {
            listBranch.Items.AddRange(RuntimeData.GetCalemBranchList());
        }

        private void timerAutoFocus_Tick(object sender, EventArgs e)
        {
            if (!txtBarcode.Focused)
            {
                txtBarcode.Focus();
            }
        }

        private void listBranch_Enter(object sender, EventArgs e)
        {
            timerAutoFocus.Enabled = false;
        }

        private void FrmImportItemFromBarcode_Enter(object sender, EventArgs e)
        {
            if (!txtBarcode.Focused)
            {
                txtBarcode.Focus();
            }

            if (timerAutoFocus.Enabled == false)
            {
                timerAutoFocus.Enabled = true;
            }
        }

        public override void FormActived()
        {
            if (!txtBarcode.Focused)
            {
                txtBarcode.Focus();
            }

            if (timerAutoFocus.Enabled == false)
            {
                timerAutoFocus.Enabled = true;
            }

            string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
            if (!string.IsNullOrEmpty(connectionString))
            {
                DBBranchConnection.ConnectionString = connectionString;
            }
        }

        private void btConnect_Click(object sender, EventArgs e)
        {
            if (timerAutoFocus.Enabled == false)
            {
                timerAutoFocus.Enabled = true;
            }

            if (string.IsNullOrEmpty(listBranch.Text))
            {
                return;
            }

            this.Enabled = false;
            try
            {
                this.UseWaitCursor = true;
                string connectionString = RuntimeData.GetDBBranchConnection(listBranch.Text);
                if (string.IsNullOrEmpty(connectionString))
                {
                    MessageBox.Show(this, string.Format("Không thể kết nối tới [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                DBBranchConnection.ConnectionString = connectionString;
                if (DBBranchConnection.TestConnection())
                {
                    PlayCompleteSound();
                    MessageBox.Show(this, string.Format("Kết nối thành công tới chi nhánh [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK);

                }
                else
                {
                    MessageBox.Show(this, string.Format("Không thể kết nối tới [{0}]", listBranch.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                this.Enabled = true;
                this.UseWaitCursor = false;
                LockWaitOrRelease(false);
                txtBarcode.Focus();
            }
        }

        private void AddItem(int itemAutoKey)
        {
            try
            {
                ItemEntity r = DataManager.Instance.BranchGetItemFromStock(itemAutoKey);
                if (r != null)
                {
                    int stt = itemView.Items.Count + 1;
                    ListViewItem item = GetItemFormCart(itemAutoKey.ToString());
                    if (item == null)
                    {
                        item = new ListViewItem(new string[] {stt.ToString(), 
                    r.autoKey.ToString(), r.name,
                    "1", r.price.ToString("#,0"), r.gender});
                        item.SubItems[clPrice.Index].Tag = r.price;
                        item.SubItems[clMSP.Index].Tag = r.id;
                        itemView.Items.Add(item);
                        item.Tag = itemAutoKey;
                    }
                    else
                    {
                        int amount = 1;
                        int.TryParse(item.SubItems[clAmount.Index].Text, out amount);
                        amount++;
                        item.SubItems[clAmount.Index].Text = amount.ToString();
                    }

                    itemView.Items[item.Index].ForeColor = Color.Blue;
                    // Need add to Queue.
                    if (DataManager.Instance.BranchAddItemToStock(r, 1))
                    {
                        if (DataManager.Instance.BranchUpdateItemAfterTransfer(r.autoKey, 1))
                        {
                            PlayCompleteSound();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.Message, "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void AddItem(string itemAutoKey)
        {
            int num = 0;
            int.TryParse(itemAutoKey, out num);
            AddItem(num);
        }

        private ListViewItem GetItemFormCart(string itemKey)
        {
            foreach (ListViewItem i in itemView.Items)
            {
                string key = i.SubItems[clMSP.Index].Text;
                if (string.Compare(itemKey, key, true) == 0)
                {
                    return i;
                }
            }

            return null;
        }

        private void PlayCompleteSound()
        {
            try
            {
                this.sound.PlaySync();
            }
            catch (Exception e)
            {
            }
        }

        private void listBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            LockWaitOrRelease(true);
        }

        private void LockWaitOrRelease(bool isLock)
        {
            this.listBranch.Enabled = !isLock;
            this.itemView.Enabled = !isLock;
            this.txtBarcode.Enabled = !isLock;
        }

        private void txtBarcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)(13))
            {
                e.Handled = true;
                AddItem(txtBarcode.Text.Trim());
                txtBarcode.Text = string.Empty;
            }
        }

    }
}
